package com.lw.leetcode.linked.b;

import com.lw.leetcode.linked.ListNode;

/**
 * Created with IntelliJ IDEA.
 * linked
 * 2074. 反转偶数长度组的节点
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/27 22:25
 */
public class ReverseEvenLengthGroups {


    public static void main(String[] args) {
        ReverseEvenLengthGroups test = new ReverseEvenLengthGroups();
        ListNode instance = ListNode.getInstance();

        ListNode listNode = test.reverseEvenLengthGroups(instance);
        System.out.println(listNode.str());
    }


    public ListNode reverseEvenLengthGroups(ListNode head) {
        ListNode item = head;
        ListNode last = null;
        int n = 1;
        flag:
        while (true) {
            int count = 0;
            ListNode node = item;
            while (node != null) {
                node = node.next;
                count++;
                if (count == n) {
                    break;
                }
            }
            if ((count & 1) == 1) {
                for (int i = 1; i < n; i++) {
                    if (item == null) {
                        break flag;
                    }
                    item = item.next;
                }
                if (item == null || item.next == null) {
                    break;
                }
            } else {
                if (last != null && last.next != null) {
                    find(last, count - 1);
                }
                break;
            }
            count = 0;
            node = item.next;
            while (node != null) {
                node = node.next;
                count++;
                if (count == n + 1) {
                    break;
                }
            }
            if ((count & 1) == 0) {
                last = find(item, count - 1);
                item = last.next;
            } else {
                break;
            }
            n += 2;
        }
        return head;
    }

    private ListNode find(ListNode node, int n) {
        ListNode returnValue = node.next;
        ListNode a = node.next;
        ListNode b = a.next;
        ListNode c = null;
        while (n > 0) {
            c = b.next;
            b.next = a;
            a = b;
            b = c;
            n--;
        }
        node.next = a;
        returnValue.next = c;
        return returnValue;
    }


}
